package com.imooc.bilibili.api;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.imooc.bilibili.domain.core.JsonResponse;
import com.imooc.bilibili.domain.user.RefreshToken;
import com.imooc.bilibili.domain.user.User;
import com.imooc.bilibili.domain.user.UserInfo;
import com.imooc.bilibili.following.service.UserFollowingService;
import com.imooc.bilibili.user.service.IRefreshTokenService;
import com.imooc.bilibili.user.service.UserInfoService;
import com.imooc.bilibili.user.service.UserService;
import com.imooc.bilibili.support.UserSupport;
import com.imooc.bilibili.util.RSAUtil;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author gcq
 * @Create 2022-05-21
 */
@RestController
public class UserApi {

    @Autowired
    private UserService userService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private UserSupport userSupport;

    @Autowired
    private UserFollowingService userFollowingService;

    @Autowired
    private IRefreshTokenService refreshTokenService;

    /**
     * 返回 rsa 公钥
     *
     * @return rsa 公钥
     */
    @GetMapping("/rsa-pks")
    public JsonResponse<String> getRsaPublicKey() {
        return new JsonResponse<>(RSAUtil.getPublicKeyStr());
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/users")
    public JsonResponse<User> addUser() {
        Long currentUserId = userSupport.getCurrentUserId();
        User user = userService.getUserInfo(currentUserId);
        return new JsonResponse<>(user);
    }

    /**
     * 添加用户
     *
     * @param user 用户
     * @return 结果
     */
    @PostMapping("/users")
    public JsonResponse<String> addUser(@RequestBody User user) {
        userService.addUser(user);
        return JsonResponse.success();
    }

    /**
     * 获取用户token信息
     *
     * @param user 用户
     * @return 当前用户token
     * @throws Exception token生成异常
     */
    @PostMapping("user-tokens")
    public JsonResponse<String> login(@RequestBody User user) throws Exception {
        String token = userService.login(user);
        return new JsonResponse<>(token);
    }

    /**
     * 更新用户信息
     *
     * @param userInfo 用户信息
     * @return 更新结果
     */
    @PutMapping("/user-infos")
    public JsonResponse<String> updateUserInfo(@RequestBody UserInfo userInfo) {
        Long currentUserId = userSupport.getCurrentUserId();
        userInfo.setUserId(currentUserId);
        userService.updateUserInfos(userInfo);
        return JsonResponse.success();
    }

    /**
     * 分页查询用户信息
     *
     * @param no
     * @param size
     * @param nick
     * @return
     */
    @GetMapping("user-infos")
    public JsonResponse<Page<UserInfo>> pageListUserInfos(@RequestParam Integer no, @RequestParam Integer size, String nick) {
        Long userId = userSupport.getCurrentUserId();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("no", no);
        jsonObject.put("size", size);
        jsonObject.put("nick", nick);
        jsonObject.put("userId", userId);
        Page<UserInfo> userInfoPage = userService.pageListUserInfos(jsonObject);
        if(userInfoPage.getTotal() > 0) {
            List<UserInfo> userInfoList = userFollowingService.checkFollowingStatus(userInfoPage.getRecords(), userId);
            userInfoPage.setRecords(userInfoList);
        }
        return new JsonResponse<>(userInfoPage);
    }

    /**
     * 用户登录
     *
     * @param user
     * @return
     * @throws Exception
     */
    @PostMapping("user-dts")
    public JsonResponse<Map<String, Object>> loginForDts(@RequestBody User user) throws Exception {
        Map<String, Object> map = userService.loginForDts(user);
        return new JsonResponse(map);
    }

    /**
     * 用户退出
     *
     * @param request
     * @return
     */
    @DeleteMapping("refresh-tokens")
    public JsonResponse<String> logout(HttpServletRequest request) {
        refreshTokenService.remove(new QueryWrapper<RefreshToken>()
                .eq("userId", userSupport.getCurrentUserId())
                .eq("refreshToken", request.getHeader("refreshToken")));
        return JsonResponse.success();
    }

    /**
     * 刷新accessToken
     * TODO 数据库中refreshToken已过期
     *
     * @param request
     * @return
     */
    @PostMapping("access-token")
    public JsonResponse<String> refreshAccessToken(HttpServletRequest request) throws Exception {
        String refreshToken = request.getHeader("refreshToken");
        String accessToken = refreshTokenService.refreshAccessToken(refreshToken);
        return new JsonResponse<>(accessToken);
    }
}